import Vue from 'vue';
import VueRouter from 'vue-router';
import { pcStaticRouters, phoneStaticRouters } from 'boot/routes';
import Store from 'src/store/index.js';

Vue.use(VueRouter);

const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err);
};

const createRouter = () => {
  const vueRouter = new VueRouter({
    mode: process.env.VUE_ROUTER_MODE,
    base: process.env.VUE_ROUTER_BASE,
    scrollBehavior: () => ({ x: 0, y: 0 }),
    routes: window.mobile ? phoneStaticRouters : pcStaticRouters,
  });
  return vueRouter;
};

const router = createRouter();

export function resetRouter() {
  const newRouter = createRouter();
  router.matcher = newRouter.matcher;
}

// 路由白名单
const whiteList = ['/app/sign', '/wechat/auth', '/yacht', '/saferemind','/yachtmenu'];

router.beforeEach((to, from, next) => {
  // 动态标题
  if (to.meta.title) {
    const { title } = to.meta;
    document.title = (title ? `${title} — ` : '') + process.env.PRODUCT_NAME;
  }
  // 在白名单直接方形
  if (whiteList.some((item) => item === to.path)) {
    next();
  } else if (to.path === '/login') {
    next();
  } else if (to.path === '/') {
    // 访问登录，但是人家有token 那么就直接进入首页
    if (localStorage.Authorization) {
      if (window.mobile) {
        next('/phone/home');
      } else {
        next('/sub-system');
      }
    } else {
      next('/login');
    }
  } else if (
    Store.state.Rule.routes === null ||
    Store.state.Rule.routes.length === 0
  ) {
    Store.dispatch('Rule/dynamicRoutes')
      .then(() => {
        next({ ...to, replace: true });
      })
      .catch(() => {
        next('/login');
      });
  } else {
    next();
  }
});

export default router;
